package com.hellowx.controller;

import com.hellowx.feignclient.ProductClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @author MagicMushroom
 * @date 2021/7/20
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private LoadBalancerClient loadBalancerClient;

    @Resource
    private RestTemplate lbRestTemplate;

    @Resource
    private ProductClient productClient;

    @GetMapping
    public Map<String,Object> test(){
//        rest 直接发起请求，没有负载均衡
        String restResult = new RestTemplate().getForObject("http://localhost:9191/product/110", String.class);
        Map<String, Object> map=new HashMap<>();
        map.put("restTemplate",restResult);

//        discoveryClient  没有负载均衡，可以解决集群
        List<ServiceInstance> productInstances = discoveryClient.getInstances("PRODUCT");
        productInstances.forEach(productInstance->{
            log.info("product host:{} port:{} uri:{}",productInstance.getHost(),productInstance.getPort(),productInstance.getUri());
        });
        String discoveryClientResult = new RestTemplate().getForObject(productInstances.get(0).getUri() + "/product/110", String.class);
        map.put("discoveryClient",discoveryClientResult);

//        loadBalancerClient 可以解决负载均衡的问题
        ServiceInstance product = loadBalancerClient.choose("PRODUCT");
        String loadBalancerClientResult = new RestTemplate().getForObject(product.getUri() + "/product/123", String.class);
        map.put("loadBalancerClient",loadBalancerClientResult);

//        @loadBalancer 简化上一个
        String lbRestTemplateResult = lbRestTemplate.getForObject("http://PRODUCT/product/321", String.class);
        map.put("lbRestTemplate",lbRestTemplateResult);

//       openFeign
        String feignResult = productClient.test(258);
        map.put("feignClient",feignResult);

        return map;
    }
}
